/**
 * ServicePlanServiceImpl.java
 * Created at 2017-11-20
 * Created by zhanghailin
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.repository.EntityDao;
import com.broadtext.common.service.impl.EntityServiceImpl;
import com.broadtext.common.utils.DateUtils;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.message.model.SysMessage;
import com.broadtext.message.model.SysMessageParam;
import com.broadtext.message.service.IMessageService;
import com.broadtext.rms.system.dao.IServicePlanDao;
import com.broadtext.rms.system.model.TmServicePlan;
import com.broadtext.rms.system.model.TmWoHistory;
import com.broadtext.rms.system.model.TmWorkOrder;
import com.broadtext.rms.system.service.IServicePlanService;

/**
 * <p>ClassName: ServicePlanServiceImpl</p>
 * <p>Description: TODO</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-20</p>
 */
@Service("servicePlanService")
public class ServicePlanServiceImpl extends EntityServiceImpl<TmServicePlan> implements IServicePlanService {
    
    @Autowired
    @Qualifier("messageService")
    IMessageService messageService;
    /**
     * 注入Dao
     */
    @Autowired
    @Qualifier("servicePlanDao")
    private IServicePlanDao servicePlanDao;
    
    
    @Autowired
    @Qualifier("servicePlanDao")
    public void setEntityDao(EntityDao<TmServicePlan> entityDao) {
        super.entityDao = entityDao;
    }
    
    

    /** (non-Javadoc)
     * <p>Title: updateRecord</p>
     * <p>Description: </p>
     * @param record
     * @return
     * @throws ServiceException
     * @see com.broadtext.common.service.impl.EntityServiceImpl#updateRecord(java.lang.Object)
     */
    @Override
    public boolean updateRecord(Object record) throws ServiceException {
        boolean flag = super.updateRecord(record);
        TmServicePlan t = (TmServicePlan)record;
        try {
            //删除消息推送，删除消息参数
            this.entityDao.deleteRecord("com.broadtext.message.model.SysMessage.deleteServicePlanMessage", t.getPkId());
            this.entityDao.deleteRecord("com.broadtext.message.model.SysMessage.deleteMessageParam", t.getPkId());
            t.setCreateUser(t.getUpdateUser());
            insertServicePlanMessage(t);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return flag;
    }



    /** (non-Javadoc)
     * <p>Title: findCustomerOpt</p>
     * <p>Description: </p>
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.IServicePlanService#findCustomerOpt()
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Object> findCustomerOpt() throws ServiceException {
        List<Object> list = new ArrayList<Object>();
        try {
            list = this.entityDao.findByQuery(
                "com.broadtext.rms.system.model.TmServicePlan.findCustomerOpt", null);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return list;
    }

    /** (non-Javadoc)
     * <p>Title: getUserNamebyLoginName</p>
     * <p>Description: </p>
     * @param loginName
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.IServicePlanService#getUserNamebyLoginName(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> getUserNamebyLoginName(String loginName) throws ServiceException {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        try {
            list = this.entityDao.findByProperty("com.broadtext.rms.system.model.TmServicePlan.getUserNamebyLoginName", loginName);
            if(list!=null&&list.size()>0) {
                return list.get(0);
            }
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return null;
    }

    /** (non-Javadoc)
     * <p>Title: getPlanById</p>
     * <p>Description: </p>
     * @param pkId
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.IServicePlanService#getPlanById(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public TmServicePlan getPlanById(String pkId) throws ServiceException {
        List<TmServicePlan> list = new ArrayList<TmServicePlan>();
        try {
            list = this.entityDao.findByProperty("com.broadtext.rms.system.model.TmServicePlan.getPlanById", pkId);
            if(list!=null&&list.size()>0){
                return list.get(0);
            }
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        return null;
    }

    /** (non-Javadoc)
     * <p>Title: deleteServicePlan</p>
     * <p>Description: </p>
     * @param idArray
     * @param updateUser
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.IServicePlanService#deleteServicePlan(java.lang.String[], java.lang.String)
     */
    @Override
    public void deleteServicePlan(String[] idArray, String updateUser) throws ServiceException {
      //循环删除 
        try {
            for (String id : idArray) {
                TmServicePlan t = new TmServicePlan();
                t.setPkId(id);
                t.setUpdateDate(new Date());
                t.setUpdateUser(updateUser);
                t.setDelFlag("1");
                //删除服务计划
                this.entityDao.updateRecord("com.broadtext.rms.system.model.TmServicePlan.updateRecord", t);
                //删除工单记录
                TmWorkOrder wo = new TmWorkOrder();
                wo.setRefId(id);
                wo.setUpdateUser(updateUser);
                wo.setUpdateDate(new Date());
                wo.setDelFlag("1");
                this.entityDao.updateRecord("com.broadtext.rms.system.model.TmWorkOrder.deleteWObyRefId", wo);
                //删除工单历史
                this.entityDao.updateRecord("com.broadtext.rms.system.model.TmWoHistory.deleteWOHistoryByRefId", id);
                //删除消息推送
                this.entityDao.deleteRecord("com.broadtext.message.model.SysMessage.deleteServicePlanMessage", id);
                this.entityDao.deleteRecord("com.broadtext.message.model.SysMessage.deleteMessageParam", t.getPkId());
            }
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /** (non-Javadoc)
     * <p>Title: saveServicePlan</p>
     * <p>Description: 注意事项，submitter存的是sys_user表中的user_id,customer存的是tm_custom表中的pk_id</p>
     * @param t
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.IServicePlanService#saveServicePlan(com.broadtext.rms.system.model.TmServicePlan)
     */
    @Override
    public void saveServicePlan(TmServicePlan t) throws ServiceException {
        try {
            //保存服务计划
            this.entityDao.insertRecord("com.broadtext.rms.system.model.TmServicePlan.insertRecord", t);
            //创建服务计划工单
            TmWorkOrder wo = new TmWorkOrder();
            wo.setPkId(UUIDUtils.getUUID());
            wo.setRefId(t.getPkId());
            //"1" 请求工单，"2" 计划工单
            wo.setWoType("2");
            wo.setCreateUser(t.getCreateUser());
            wo.setCreateDate(new Date());
            wo.setDelFlag("0");
            this.entityDao.insertRecord("com.broadtext.rms.system.model.TmWorkOrder.insertRecord", wo);
            //保存工单历史记录--创建工单
            TmWoHistory woHistory = new TmWoHistory();
            woHistory.setPkId(UUIDUtils.getUUID());
            woHistory.setWoId(wo.getPkId());
            woHistory.setOperatorName(t.getUpdateUser());
            woHistory.setOperator(t.getSubmitterName());
            woHistory.setOperatingDate(t.getCreateDate());
            woHistory.setWoStatus("0");
            woHistory.setDelFlag("0");
            this.entityDao.insertRecord("com.broadtext.rms.system.model.TmWoHistory.insertRecord", woHistory);
            //推送消息
            insertServicePlanMessage(t);
            
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }

    /** (non-Javadoc)
     * <p>Title: checkRepeatPlanCode</p>
     * <p>Description: </p>
     * @param planCode
     * @param pkId
     * @return
     * @throws ServiceException
     * @see com.broadtext.rms.system.service.IServicePlanService#checkRepeatPlanCode(java.lang.String, java.lang.String)
     */
    @Override
    public Boolean checkRepeatPlanCode(String planCode, String pkId) throws ServiceException {
        Boolean flag = true;
        Map<String, Object> queryMap = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(planCode)){
            queryMap.put("planCode", planCode);
        }
        if(StringUtils.isNotBlank(pkId)){
            queryMap.put("pkId", pkId);
        }
        long count = 0 ;
        try {
            count = this.servicePlanDao.checkRepeatPlanCode(queryMap);
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
        if(count!=0){
            flag = false;
        }
        return flag;
    }
    
    @SuppressWarnings("unchecked")
    private String getUserPrimaryKey(String loginName) throws DaoException {
        String pkId = "";
        List<String> list = new ArrayList<String>();
        list = this.entityDao.findByProperty("com.broadtext.message.model.SysMessage.getUserPrimaryKey", loginName);
        if(list!=null&&list.size()>0&&list.get(0)!=null) {
            pkId = list.get(0);
        }
        return pkId;
    }
    
    private Long insertServicePlanMessage(TmServicePlan t) throws DaoException, ParseException {
        Long messageId = null;
        if(StringUtils.isNotBlank(t.getPlanEndDateStr())&&t.getPlanEndDate()!=null) {
            SysMessage message = new SysMessage();
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date pushDate = format.parse(DateUtils.getPastDate(7, t.getPlanEndDate()));
            String receiver = getUserPrimaryKey(t.getCreateUser());
            message.setSender("system");
            message.setReceiver(receiver);
            message.setDelFlag("0");
            message.setMessageTitle("您有一条即将过期的服务计划，请注意查看");
            //拼装消息内容
            StringBuffer content = new StringBuffer("您的服务计划“");
            content.append(t.getPlanContent());
            content.append("”还有不足7天即将到期，您可以在“运营售后管理--服务工单”查看详情。");
            
            message.setMessageContent(content.toString());
            message.setMessageStatus("0");//未读
            message.setCreateUser(t.getCreateUser());
            message.setPushDate(pushDate);
            message.setCreateDate(now);
            message.setMessageType("2");//服务动态
            messageId = this.messageService.insertMessage(message);
            
            SysMessageParam param = new SysMessageParam();
            param.setPkId(UUIDUtils.getUUID());
            param.setMessageId(messageId);
            param.setParamCode("service_plan_id");
            param.setParamName("服务计划id");
            param.setParamValue(t.getPkId());
            param.setCreateDate(now);
            param.setCreateUser(t.getCreateUser());
            this.entityDao.insertRecord("com.broadtext.message.model.SysMessage.insertMessageParam",param);
            
        }
        return messageId;
    }
    

}
